package com.javaweb.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @desc:
 * @author: Ping
 * @date: 2024/11/23 11:12
 */

//@Component
@Slf4j
//@ConfigurationProperties(prefix = "filter")
//@EnableConfigurationProperties
public class UrlFilter implements Filter {
    @Value("${filter.max-req-size}")
    private int maxReqNum ;
    private int reqNum = 0;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        log.info("init filter with param maxReqNum:{}",maxReqNum );

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("accepted url: {}", ((HttpServletRequest)servletRequest).getRequestURI()) ;
        if (reqNum < maxReqNum) {
            reqNum++;
            log.info("request num:{}",reqNum);
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            log.info("request num reach max limit:{}",maxReqNum);
            servletResponse.getWriter().write("request num reach max limit");
        }
    }
}
